﻿using B.S.BasicData.Infastructure.Implement;
using B.S.BasicData.Infastructure.Interface;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace B.S.BasicData.Api.Write.Extensions
{
    /// <summary>
    /// 扩展类
    /// </summary>
    public static class ServiceCollectionExtension
    {
        /// <summary>
        /// 服务扩展类
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddServices(this IServiceCollection services)
        {
            //仓储
            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));


            return services;
        }
        /// <summary>
        /// 连接数据库封装
        /// </summary>
        /// <typeparam name="MyDbContext">Ef上下文</typeparam>
        /// <param name="services">依赖注入容器</param>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="enableSqllog">是否启用sql日志记录</param>
        /// <returns></returns>
        public static IServiceCollection AddDbContextService<MyDbContext>(this IServiceCollection services, string? connectionString, bool enableSqllog) where MyDbContext : DbContext
        {
            return services.AddDbContext<MyDbContext>(builder =>
            {
                //设置使用SQL Server作为数据库提供程序
                builder.UseSqlServer(connectionString, action =>
                {
                    //当数据库连接失败时自动重试
                    action.EnableRetryOnFailure(
                        maxRetryCount: 10,//最多重试10次
                        maxRetryDelay: TimeSpan.FromSeconds(60),//最大重试延迟60秒
                        errorNumbersToAdd: null);//未指定特定错误码进行重试
                }).EnableSensitiveDataLogging();
                //根据传入的参数决定是否启用SQL语句日志记录
                if (enableSqllog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure
                       .AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                       .AddConsole();
                    }));
                }
            });
        }
        /// <summary>
        /// 注册Jwt扩展方法
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="builder"></param>
        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    //取出私钥
                    var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        //验证发布者
                        ValidateIssuer = true,
                        ValidIssuer = builder.Configuration["Authentication:Issuer"],
                        //验证接受者
                        ValidateAudience = true,
                        ValidAudience = builder.Configuration["Authentication:Audience"],
                        //验证是否过期
                        ValidateLifetime = true,
                        IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                    };
                });
        }
    }
}
